angular.module('starter.controllers', [])

.controller('LoginCtrl', function($scope, $timeout,  $state, $ionicPopup, $http, $rootScope) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  // Form data for the login modal

  if (typeof  localStorage.storeUser!== 'undefined' &&  localStorage.storeUser!=null) {
    console.log(localStorage.storeUser + ' pwd ' + localStorage.storePwd);
    var userJson = {};
    userJson["username"] = localStorage.storeUser;
    userJson["password"] = localStorage.storePwd;
    $http({
      method : 'POST',
      url : 'http://123.57.155.162:8081/api/Login/PostLogin',
      data : userJson
    }).success(function(data, status, headers, config) {
      if (data != null && data.length > 9) {
        $scope.showAlert('用户名密码错误！');
      } else if (data != null) {
        var imgArray = data.split("|");
        console.log("login" + data + imgArray[1]);
        $rootScope.accId = imgArray[0];
        $rootScope.privilege = imgArray[1];
        $state.go('app.home');
      }
    }).error(function(data, status, headers, config) {
      //console.log(status);
      $scope.showAlert('无法连接服务器!');
    });
  }

  $scope.login = function(user) {
    if(typeof(user)=='undefined'){
      $scope.showAlert('请输入用户名和密码！');
      return false;
    }
    var userJson = {};
    userJson["username"] = user.username;
    userJson["password"] = user.password;
    $http({
      method : 'POST',
      url : 'http://123.57.155.162:8081/api/Login/PostLogin',
      data : userJson
    }).success(function(data, status, headers, config) {
      if (data != null && data.length > 9) {
        $scope.showAlert('用户名密码错误！');
      } else if (data != null) {
        var imgArray = data.split("|");
        console.log("login" + data + imgArray[1]);
        $rootScope.accId = imgArray[0];
        $rootScope.privilege = imgArray[1];
        window.localStorage.setItem('storeUser', user.username);
        window.localStorage.setItem('storePwd', user.password);
        $state.go('app.home');
      }
    }).error(function(data, status, headers, config) {
      //console.log(status);
      $scope.showAlert('无法连接服务器!');
    });
  };
  
  // An alert dialog
  $scope.showAlert = function(msg) {
    var alertPopup = $ionicPopup.alert({
      title: '警告',
      template: msg
    });
  };
})

.controller('HomeCtrl', function($scope, $state, $ionicModal, $ionicPopup, $cordovaFileTransfer,
            $http, $rootScope, $cordovaBarcodeScanner, Camera) {
  $scope.deviceData = {};
  $scope.currentDevice = '选择设备';
  $scope.devId = '';
  $scope.devices = [];
  $scope.images = [];
  $scope.order = {};
  $scope.issueResponse = [];

  var _viewModal;

  $scope.loadModal = function(){
    $ionicModal.fromTemplateUrl('templates/slider.html', {
      scope: $scope,
      animation: 'fade-in'
    }).then(function(modal) {
      _viewModal = modal;
      $scope.openModal();
    });
  };
  $scope.openModal = function() {
    _viewModal.show();
  };

  $scope.closeImgModal = function() {
    _viewModal.hide();
  };

  $scope.removeImg = function(imgIdx) {
    console.log('remove image ' + imgIdx);
    $scope.images.splice(imgIdx, 1);
    $scope.closeImgModal();
  };

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/devices.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  $scope.scanBarcode = function() {
    $cordovaBarcodeScanner
      .scan()
      .then(function(barcodeData) {
        var imgArray = barcodeData.text.split("|");
        if (imgArray.length == 2) {
          $scope.devId = imgArray[0];
          $scope.currentDevice = imgArray[1];
        }
      }, function(err) {
        console.log(err);
      })
  };

  $scope.clearSearch = function(device) {
    //console.log('click one item' + JSON.stringify(device));
    $scope.currentDevice = device.name;
    $scope.devId = device.id;
    console.log("DevId = " + $scope.devId);
    $scope.modal.hide();
  };

  $scope.listDevice = function() {
    $http({
      method : 'GET',
      url : 'http://123.57.155.162:8081/api/device/getDevicesById/' + $rootScope.accId,
    }).success(function(data, status, headers, config) {
      $scope.devices = data;
      $scope.modal.show();
    }).error(function(data, status, headers, config) {
      console.log(status);
    });
  };

  // Triggered in the login modal to close it
  $scope.closeDevice = function() {
    $scope.modal.hide();
  };

  $scope.selectedDevice = function() {
    if ($scope.deviceData.dv != null)
    {
      $scope.currentDevice = $scope.deviceData.dv.name;
      $scope.devId = $scope.deviceData.dv.id;
      console.log("DevId = " + $scope.devId);
      $scope.modal.hide();
    }
    else
    {
      $scope.showAlert('请选择设备!');
    }
  };

  $scope.createOrder = function() {
    //data validation
    if ($scope.currentDevice == '选择设备')
    {
      $scope.showAlert('请选择设备!');
      return;
    }
    if ($scope.order.reason == undefined)
    {
      $scope.showAlert('请输入设备故障原因!');
      return;
    }
    var orderJson = {};
    var imageJson = {};
    orderJson["status"] = 1;
    orderJson["issueimg"] = '';
    orderJson["device"] = parseInt($scope.devId);
    orderJson["reason"] = $scope.order.reason;
    orderJson["reporter"] = parseInt($rootScope.accId);
    //upload picture
    //var server = encodeURI('http://123.57.155.162:8081/api/order/PostUpload');
    var imgLen = $scope.images.length;
    $scope.issueResponse = [];
    if (imgLen > 0)
    {
      $rootScope.$broadcast('loading:show');
      var imgIndex;
      for(imgIndex in $scope.images)
      {
        Camera.toBase64Image($scope.images[imgIndex]).then(function(success_resp) {
          imageJson["imageData"] = success_resp.imageData;
          $http({
            method : 'POST',
            url : 'http://123.57.155.162:8081/api/order/PostUpload',
            data : imageJson
          }).success(function(data, status, headers, config) {
            console.log('post upload ' + data);
            $scope.issueResponse.push(data);
            orderJson["issueimg"] = orderJson["issueimg"] + data + ';';
            if ($scope.issueResponse.length >= imgLen) {
              $rootScope.$broadcast('loading:hide');
              //console.log(JSON.stringify(orderJson));
              $http({
                method : 'POST',
                url : 'http://123.57.155.162:8081/api/order/PostData',
                data : orderJson
              }).success(function(data, status, headers, config) {
                if (data.length > 7) {
                  $scope.showAlert(data.replace(/\"/g,""));
                } else {
                  $scope.showAlert('工单号' + data.replace(/\"/g,"") + '已成功创建!');
                  $scope.order.reason = '';
                  $scope.images = [];
                }
              }).error(function(data, status, headers, config) {
                $scope.showAlert('工单生成错误！');
              });
            }
          }).error(function(data, status, headers, config) {
            $scope.showAlert('上传图片出错！');
          });

        }, function(fail_resp) {

        });
      }
    }
    else
    {
      $http({
        method : 'POST',
        url : 'http://123.57.155.162:8081/api/order/PostData',
        data : orderJson
      }).success(function(data, status, headers, config) {
        if (data.length > 7)
        {
          $scope.showAlert(data.replace(/\"/g,""));
        }
        else
        {
          $scope.showAlert('工单号' + data.replace(/\"/g,"") + '已成功创建!');
          $scope.order.reason = '';
          $scope.images = [];
        }
      }).error(function(data, status, headers, config) {
        $scope.showAlert('工单生成错误！');
      });
    }
  };

  $scope.onSwipe = function(idx) {
//    $scope.images.splice(idx, 1);
//    console.log('drag...' + idx + ' img ' + $scope.images.length);
    console.log('show image' + idx);
    Camera.toBase64Image($scope.images[idx])
      .then(function(success_resp) {
        $scope.order.imgsrc = "data:image/jpg;base64," + success_resp.imageData;
        $scope.order.viewIdx = idx;
        $scope.loadModal();
      }, function(fail_resp) {
      })
  };

  $scope.getPhoto = function() {
    //Max three files
    if ($scope.images.length >= 3)
    {
      $scope.showAlert('不能超过三张图片!');
      return;
    }
    Camera.getPicture().then(function(imageURI) {
      $scope.images.push(imageURI);
      //Camera.toBase64Image(imageURI);
    }, function(err) {
      console.err(err);
    }, {
      quality : 75,
      allowEdit : true,
      targetWidth: 300,
      targetHeight: 300,
      saveToPhotoAlbum: false
    });
  };

  // An alert dialog
  $scope.showAlert = function(msg) {
    var alertPopup = $ionicPopup.alert({
      title: '提示',
      template: msg
    });
  };
})

.controller('RepairDetailCtrl', function($scope, $stateParams, $cordovaCapture, $ionicPopup,
            $state, $http, $ionicModal, $rootScope, Orders, Camera) {
  $scope.order = Orders.get($stateParams.repairId);

  var repairData = {};
  $scope.repair = {};
  //set image
  $scope.issueImages = [];
  $scope.fixImages = [];
  $scope.images = [];

  repairData["id"] = $scope.order.id;

  var _viewModal;

  $scope.loadModal = function(){
    $ionicModal.fromTemplateUrl('templates/resetorder.html', {
      scope: $scope,
      animation: 'fade-in'
    }).then(function(modal) {
      _viewModal = modal;
      $scope.openModal();
    });
  };
  $scope.openModal = function() {
    _viewModal.show();
  };

  $scope.closeImgModal = function() {
    _viewModal.hide();
  };

  $scope.removeImg = function(imgIdx) {
    console.log('remove image ' + imgIdx);
    $scope.images.splice(imgIdx, 1);
    $scope.closeImgModal();
  };

  if ($scope.order.issueimg != '')
  {
    $scope.imageDetails = [];
    var imgArray = $scope.order.issueimg.split(";");
    imgArray = imgArray.filter(function(e){return e});
    while((img = imgArray.pop()) != null)
    {
      $scope.issueImages.push('http://123.57.155.162:8081' + img);
    }
  }

  if ($scope.order.fiximg != '')
  {
    $scope.imageDetails = [];
    var imgArray = $scope.order.fiximg.split(";");
    imgArray = imgArray.filter(function(e){return e});
    while((img = imgArray.pop()) != null)
    {
      $scope.fixImages.push('http://123.57.155.162:8081' + img);
    }
  }

  $scope.getPhoto = function() {
    //Max three files
    if ($scope.images.length >= 3)
    {
      $scope.showAlert('不能超过三张图片!');
      return;
    }
    Camera.getPicture().then(function(imageURI) {
      $scope.images.push(imageURI);
      //Camera.toBase64Image(imageURI);
    }, function(err) {
      console.err(err);
    }, {
      quality : 75,
      allowEdit : true,
      targetWidth: 300,
      targetHeight: 300,
      saveToPhotoAlbum: false
    });
  };

  $scope.captureVideo = function() {
    var options = { limit: 1, duration: 20 };

    $cordovaCapture.captureVideo(options).then(function(videoData) {
      // Success! Video data is here
    }, function(err) {
      // An error occurred. Show a message to the user
    });
  };

  $scope.confirmOrder = function() {
    repairData["status"] = 3;
    $http({
      method : 'POST',
      url : 'http://123.57.155.162:8081/api/order/PostRepair',
      data : repairData
    }).success(function(data, status, headers, config) {
      var alertPopup = $ionicPopup.alert({
        title: '提示',
        template: data
      });
      alertPopup.then(function(res) {
        $state.go('app.repairs');
      });
      Orders.remove($scope.order);
    }).error(function(data, status, headers, config) {
    });
  };

  $scope.resetDone = function() {
    console.log('Get details ' + $scope.repair.detailInfo);
    repairData["status"] = 2;
    repairData["repairinfo"] = $scope.repair.detailInfo;
    repairData["repairimg"] = '';
    //upload pictures
    var imgLen = $scope.images.length;
    $scope.repairResponse = [];
    if (imgLen > 0)
    {
      $rootScope.$broadcast('loading:show');
      var imgIndex;
      for(imgIndex in $scope.images)
      {
        Camera.toBase64Image($scope.images[imgIndex])
          .then(function (success_resp) {
            // Success!
            $http({
              method : 'POST',
              url : 'http://123.57.155.162:8081/api/order/PostUpload',
              data : success_resp
            }).success(function(data, status, headers, config) {
              console.log('post upload ' + data);
              $scope.repairResponse.push(data);
              repairData["repairimg"] = repairData["repairimg"] + data + ';';
              if ($scope.repairResponse.length >= imgLen)
              {
                $rootScope.$broadcast('loading:hide');
                $http({
                  method : 'POST',
                  url : 'http://123.57.155.162:8081/api/order/PostRepair',
                  data : repairData
                }).success(function(data, status, headers, config) {
                  var alertPopup = $ionicPopup.alert({
                    title: '提示',
                    template: data
                  });
                  alertPopup.then(function(res) {
                    $scope.closeImgModal();
                    $state.go('app.repairs');
                  });
                  Orders.remove($scope.order);
                }).error(function(data, status, headers, config) {
                });
                }
              }).error(function(data, status, headers, config) {

              });
            }, function (fail_resp) {
              // Error
              $rootScope.$broadcast('loading:hide');
            });
      }
    } else {
      $http({
        method : 'POST',
        url : 'http://123.57.155.162:8081/api/order/PostRepair',
        data : repairData
      }).success(function(data, status, headers, config) {
        var alertPopup = $ionicPopup.alert({
          title: '提示',
          template: data
        });
        alertPopup.then(function(res) {
          $scope.closeImgModal();
          $state.go('app.repairs');
        });
        Orders.remove($scope.order);
      }).error(function(data, status, headers, config) {
      });
    }

  };

  $scope.resetOrder = function() {
    $scope.loadModal();
  };
})

.controller('RepairsCtrl', function($scope, $cordovaBarcodeScanner, $ionicPopup, Orders) {
  $scope.orders = [];
  Orders.all().then(function(orders){
    $scope.orders = orders;
  });
  $scope.remove = function(order) {
    Orders.remove(order);
  };

  $scope.doRefresh = function() {
    console.log('refreshing...');
    Orders.all().then(function(orders){
      $scope.orders = orders;
    });
    $scope.$broadcast('scroll.refreshComplete');
  };

  $scope.scanRepairs = function() {
    $cordovaBarcodeScanner
      .scan()
      .then(function(barcodeData) {
        console.log('Get barcode for repair' + barcodeData.text);
        var imgArray = barcodeData.text.split("|");
        if (imgArray.length == 2) {
          $scope.orders = $scope.orders.filter(function(item) {
            return (item.deviceName == imgArray[1]);
          })
        }
      }, function(err) {
        console.log(err);
      })
  };
})

.controller('ChatsCtrl', function($scope, $ionicHistory, $cordovaBarcodeScanner, $ionicPopup, Chats) {
  $scope.chats = [];
  Chats.all().then(function(chats){
    $scope.chats = chats;
  });
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };

  $scope.doRefresh = function() {
    console.log('refreshing...');
    Chats.all().then(function(chats){
      $scope.chats = chats;
    });
    $scope.$broadcast('scroll.refreshComplete');
  };

  $scope.scanOrders = function() {
    $cordovaBarcodeScanner
      .scan()
      .then(function(barcodeData) {
        var imgArray = barcodeData.text.split("|");
        if (imgArray.length == 2) {
          $scope.chats = $scope.chats.filter(function(item) {
            return (item.deviceName == imgArray[1]);
          })
        }
      }, function(err) {
        console.log(err);
      })
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, $ionicLoading, $http, $state,
            $ionicPopup, $ionicModal, $cordovaFileTransfer, $rootScope, Chats, Camera) {
  $scope.order = {};
  var orderJson = {};
  $scope.chat = Chats.get($stateParams.chatId);
  orderJson["id"] = $scope.chat.id;
  //set image
  $scope.images = [];
  $scope.imageDetails = [];
  var _viewModal;

  $scope.loadModal = function(){
    $ionicModal.fromTemplateUrl('templates/slider.html', {
      scope: $scope,
      animation: 'fade-in'
    }).then(function(modal) {
      _viewModal = modal;
      $scope.openModal();
    });
  };
  $scope.openModal = function() {
    _viewModal.show();
  };

  $scope.$on('$destroy', function() {
    try{
      //_viewModal.remove();
    } catch(err) {
      console.log(err.message);
    }
  });

  $scope.onSwipe = function(idx) {
    //$scope.images.splice(idx, 1);
    //console.log('drag...' + idx + ' img ' + $scope.images.length);
    console.log('show image' + idx);
    Camera.toBase64Image($scope.images[idx])
      .then(function(success_resp) {
        $scope.order.imgsrc = "data:image/jpg;base64," + success_resp.imageData;
        $scope.order.viewIdx = idx;
        $scope.loadModal();
      }, function(fail_resp) {
      })
  };

  $scope.closeImgModal = function() {
    _viewModal.hide();
  };
  // Create the order detail
  $ionicModal.fromTemplateUrl('templates/orderdetail.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  $scope.showImage = function(idx) {
    console.log('show image' + idx);
    $scope.order.imgsrc = $scope.imageDetails[idx];
    $scope.loadModal();
  };

  $scope.removeImg = function(imgIdx) {
    console.log('remove image ' + imgIdx);
    $scope.images.splice(imgIdx, 1);
    $scope.closeImgModal();
  };

  // Triggered in the login modal to close it
  $scope.closeModal = function() {
    $scope.viewHide = false;
    $scope.modal.hide();
  };

  $scope.viewOrder = function() {
    if ($scope.chat.issueimg != '')
    {
      $scope.imageDetails = [];
      $scope.imageRepairs = [];
      var imgArray = $scope.chat.issueimg.split(";");
      imgArray = imgArray.filter(function(e){return e});
      while((img = imgArray.pop()) != null)
      {
        $scope.imageDetails.push('http://123.57.155.162:8081' + img);
      }

      if (typeof($scope.chat.repairimg) != "undefined" && $scope.chat.repairimg != null)
      {
        imgArray = $scope.chat.repairimg.split(";");
        imgArray = imgArray.filter(function(e){return e});
        while((img = imgArray.pop()) != null)
        {
          $scope.imageRepairs.push('http://123.57.155.162:8081' + img);
        }
      }
    }

    $scope.order.issuereason = $scope.chat.reason;
    $scope.order.issuerepair = $scope.chat.repairinfo;
    $scope.order.id = $scope.chat.id;
    $scope.order.reporterId = $scope.chat.reporter;
    $scope.viewHide = true;
    $scope.modal.show();
  };

  $scope.getPhoto = function() {
    //Max three files
    if ($scope.images.length >= 3)
    {
      $scope.showAlert('不能超过三张图片!');
      return;
    }
    Camera.getPicture().then(function(imageURI) {
      $scope.images.push(imageURI);
    }, function(err) {
      console.err(err);
    }, {
      quality : 75,
      allowEdit : true,
      targetWidth: 300,
      targetHeight: 300,
      saveToPhotoAlbum: false
    });
  };

  $scope.processOrder = function() {
    if ($scope.order.resolution == undefined || $scope.order.resolution == '')
    {
      $scope.showAlert('请输入解决方案!');
      return;
    }
    orderJson["resolution"] = $scope.order.resolution;
    orderJson["fiximg"] = '';
    //upload pictures
    var imgLen = $scope.images.length;
    $scope.fixResponse = [];
    if (imgLen > 0)
    {
      $rootScope.$broadcast('loading:show');
      var imgIndex;
      for(imgIndex in $scope.images)
      {
        Camera.toBase64Image($scope.images[imgIndex])
          .then(function (success_resp) {
            // Success!
            $http({
              method : 'POST',
              url : 'http://123.57.155.162:8081/api/order/PostUpload',
              data : success_resp
            }).success(function(data, status, headers, config) {
              console.log('post upload ' + data);
              $scope.fixResponse.push(data);
              orderJson["fiximg"] = orderJson["fiximg"] + data + ';';
              if ($scope.fixResponse.length >= imgLen)
              {
                $rootScope.$broadcast('loading:hide');
                console.log(JSON.stringify(orderJson));
                $http({
                  method : 'POST',
                  url : 'http://123.57.155.162:8081/api/order/PostDone',
                  data : orderJson
                }).success(function(data, status, headers, config) {
                    var alertPopup = $ionicPopup.alert({
                      title: '提示',
                      template: data
                    });
                    alertPopup.then(function(res) {
                      $state.go('app.chats');
                    });
                    Chats.remove($scope.chat);
                    $scope.order.resolution = '';
                    $scope.images = [];
                  }).error(function(data, status, headers, config) {
                    $scope.showAlert(status);
                  });
                }
              }).error(function(data, status, headers, config) {

              });
            }, function (fail_resp) {
              // Error
              $rootScope.$broadcast('loading:hide');
            });
      }
    } else {
      $http({
        method : 'POST',
        url : 'http://123.57.155.162:8081/api/order/PostDone',
        data : orderJson
      }).success(function(data, status, headers, config) {
        var alertPopup = $ionicPopup.alert({
          title: '提示',
          template: data
        });
        alertPopup.then(function(res) {
          $state.go('app.chats');
        });
        Chats.remove($scope.chat);
        $scope.order.resolution = '';
      }).error(function(data, status, headers, config) {

      });
    }
  };

  // An alert dialog
  $scope.showAlert = function(msg) {
    var alertPopup = $ionicPopup.alert({
      title: '提示',
      template: msg
    });
  };
})

.controller('TabCtrl', function($scope, $rootScope) {
  if (parseInt($rootScope.privilege) >=4
    && parseInt($rootScope.privilege) <8) {
    $scope.orderPrivilege = true;
    $scope.accountPrivilege = true;
  } else if (parseInt($rootScope.privilege) >=8){
    $scope.orderPrivilege = true;
    $scope.repairPrivilege = true;
    $scope.accountPrivilege = true;
  } else {
    $scope.accountPrivilege = true;
  }
})

.filter('searchDevices', function() {
  return function (items, query) {
    var filtered = [];
    var letterMatch = new RegExp(query, 'i');
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (query) {
        if (letterMatch.test(item.name.substring(0, query.length))) {
          filtered.push(item);
        }
      } else {
        filtered.push(item);
      }
    }
    return filtered;
  };
})

.controller('AccountCtrl', function($scope, $state, $ionicHistory, $timeout) {
  $scope.settings = {
    enableFriends: true
  };

  $scope.logout = function() {
    window.localStorage.removeItem('storeUser');
    window.localStorage.removeItem('storePwd');
    $state.go('login');
    $timeout(function () {
      $ionicHistory.clearCache();
      $ionicHistory.clearHistory();
    },300)
  };
});
